<?php

namespace EM\NewsBundle\Controller;
use EM\NewsBundle\Entity\News;
use EM\NewsBundle\Entity\NewsId;
use EM\NewsBundle\Entity\NewsCategories;
use EM\NewsBundle\Entity\Geography;
use EM\NewsBundle\Entity\Languages;
use EM\NewsBundle\Entity\Countries;
use EM\NewsBundle\Entity\Users;
use EM\NewsBundle\Form\NewType;
use EM\NewsBundle\Form\NewExtraType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Util\Inflector;

class NewController extends Controller
{
   
        public function createAction(Request $request){
                $user = $this->container->get('security.context')->getToken()->getUser();
                $idNew=null;
               // $utils = $this->get('em_service');
		//var_dump($countries);
              //  exit();
                $countries=$this->getDoctrine()->getRepository('EMNewsBundle:UserGeoLangSettings')->findByUser(array('user'=>$user->getId()));
                $repository=$this->getDoctrine()->getRepository('EMNewsBundle:Categories');
		$geo_rep=$this->getDoctrine()->getRepository('EMNewsBundle:Geography');
		$categories = $repository->findAll();
		$geo = $geo_rep->findAll();
		$new = new News();
		$new->setDateCreated( new \DateTime());                
                $new->setDateUpdated( new \DateTime());
                $new->setKeywords("1");
               
                $form = $this->createForm(new NewType(), $new);
                
		$request = $this->getRequest();
                
		//-- En caso de que el request haya sido invocado por POST
		//   procesaremos el formulario
		if($request->getMethod() == 'POST')
		{
			//-- Pasamos el request el método bindRequest() del objeto 
			//   formulario el cual obtiene los datos del formulario
			//   y los carga dentro del objeto Article que está contenido
			//   también dentro del objeto Type
			$cat=$this->get('request')->request->get('cat');
			$author=$this->get('request')->request->get('author');
			$countryId=$this->get('request')->request->get('countryId');
                        $langId=$this->get('request')->request->get('lang');
                        $language=$this->getDoctrine()->getRepository('EMNewsBundle:Languages')->find($langId);
                        $new->setLanguage($language);
                        $countryc=null;
                        foreach ($geo as $c){ //busca el objeto que coincida con el id de geografia para insertarlo.
                            if($c->getId()==$countryId)
                            {
                               $new->setGeography($c);
                               $countryc=$c;
                            }
                            
                        }
			$form->bind($request);
                        
                       if($form->isValid()){
                           //Generate slug 
                         
                           $new->setSlug(Inflector::urlize($new->getTitle()));
                         //  $new->setSlug(utf8_encode($new->getTitle()));
                           $slug=$new->getSlug();
                           //Encoding data
                                $new->setTitle(utf8_encode($new->getTitle()));
                                $new->setMetaDescription(utf8_encode($new->getMetaDescription()));
                                $new->setContent(utf8_encode($new->getContent()));
                                
                                $new->setAuthor((int)$author);                              
				$em = $this->getDoctrine()->getManager();
				$em->persist($new);
				if(!$em->flush()){
                                $idNew=$new->getId();
                                /*Save into the news_ids table*/
                                $newrel = new NewsId();
                                $newrel->setNewOriginal($new);
                                $newrel->setNewTranslated(null);
				$em->persist($newrel);
                                

				//$form = $this->createForm(new NewType(), $new);
                                if($cat!=""){
                                    foreach($cat as $ca){
                                            $newcat= new NewsCategories();
                                            $newcat->setCategoryId($ca);
                                            $newcat->setNewsId($new->getId());
                                            $em->persist($newcat);
                                            $em->flush();
                                    }
                                }
                                $new = new News();
                                $new->setGeography($countryc);
                                $form = $this->createForm(new NewType(), $new);
				return $this->render('EMNewsBundle:New:new.html.twig', array(
				'form' => $form->createView(),
				'step' =>2,
				'status_form'=>1,
				'url1'=>$this->createUrlAction(utf8_decode($slug)),
				'idNew'=>$idNew,
				//'countryc'=>$countryc,
				'categories'=>$categories,
                                ));
                                }
                                else
                                {
                                    return $this->render('EMNewsBundle:New:new.html.twig', array(
                                        'form' => $form->createView(),
                                        'step' =>1,
                                        'status_form'=>2,
                                        'categories'=>$categories,
                                      //  'countryc'=>$countryc,
                                        'geography'=>$geo,
                                        ));
                                }
			}
			else
			{
			return $this->render('EMNewsBundle:New:new.html.twig', array(
			'form' => $form->createView(),
                        'step' =>1,
			'status_form'=>2,
			'categories'=>$categories,
                      //  'countryc'=>$countryc,
                        'geography'=>$geo,
                        ));
			}
		
		}
			
		return $this->render('EMNewsBundle:New:new.html.twig', array(
			'form' => $form->createView(),
                        'step' =>1,
			'status_form'=>0,
			'categories'=>$categories,
			'geography'=>$geo,
                        'countries'=>$countries,
		));
   }
        public function createTranslatedAction(Request $request,$idNew){
        $new = new News();
        $new->setDateCreated( new \DateTime());                
        $new->setDateUpdated( new \DateTime());
	
        $request = $this->getRequest();	
        $idNew1=$idNew;
        $new1= $this->getDoctrine()->getRepository('EMNewsBundle:News')->find($idNew);
         //save language default
        $languages= $this->getDoctrine()->getRepository('EMNewsBundle:Languages')->find(1);
        //save author
        $user = $this->container->get('security.context')->getToken()->getUser();
        $new->setAuthor($user->getId());
        $new->setAuthor($user->getId());
        $new->setLanguage($languages); 
        $new->setSource($new1->getSource()); 
        $new->setUrl($new1->getUrl()); 
        $new->setGeography($new1->getGeography()); 
        $new->setImage($new1->getImage()); 
       
        $form = $this->createForm(new NewType(), $new);
        
           if($request->getMethod() == 'POST'){
            $form->bind($request);
           
            if($form->isValid())
            {
               
                $new->setSlug(Inflector::urlize($new->getTitle()));
                $em = $this->getDoctrine()->getManager();
                $em->persist($new);
                if(!$em->flush()){
                     /*Relation between both*/
                               // $newrel = new NewsId();
                                $newrel=$this->getDoctrine()->getRepository('EMNewsBundle:NewsId')->findOneBy(array('newOriginal'=>$idNew1));
                               // $newrel->setNewOriginal($new1);
                                $newrel->setNewTranslated($new);
				$em->persist($newrel);
                                if(!$em->flush()){
                                    return $this->render('EMNewsBundle:New:_form3.html.twig', array(
                                    //'form' => $form->createView(),
                                    'status_form'=>3,
                                    'newrel'=>$newrel,
                                    )); 
                                }
                                else //si no pudo guardar la relacion entre ambos posts 
                                {
                                    return $this->render('EMNewsBundle:New:_form2.html.twig', array(
                                                    'form' => $form->createView(),
                                                    'status_form'=>2,
                                                    'idNew'=>$idNew1,
                                                    ));
                                }
                }
                else
                {
                    return $this->render('EMNewsBundle:New:_form2.html.twig', array(
                                    'status_form'=>2,
                                        'form' => $form->createView(),
                                        'status_form'=>2,
                                        'idNew'=>$idNew1,
                                    ));
                }
                // Despues de haber guardado la segunda traduccion se debe de guardar los id's de 
             }
             else
             {
               //  print_r($form);
               //  exit();
            //  print_r( $this->getErrorMessages($form));  
            //  exit();
//               return $this->render('EMNewsBundle:New:_form2.html.twig', array(
//                                    'status_form'=>2,
//                                    'form' => $form->createView(),
//                                    'idNew'=>$idNew1,
//                                   ));  
               // print_r($new);
               //  print_r($form);
               //  exit();
               //  return $form;
             }
         }
         else
         {
            // return $this->redirect($this->generateUrl('em_news'));
            return $this->render('EMNewsBundle:New:new.html.twig', array(
				'form' => $form->createView(),
				'step' =>2,
				'status_form'=>0,
				//'url1'=>$this->createUrlAction(utf8_decode($slug)),
				'idNew'=>$idNew,
				//'categories'=>$categories,
                                )); 
             
         }
        }

	public function showAction($status){
	
		$repository=$this->getDoctrine();
		$n_table=$repository->getRepository('EMNewsBundle:News');
		$cat_table=$repository->getRepository('EMNewsBundle:Categories');
		$catnew_table=$repository->getRepository('EMNewsBundle:NewsCategories');
		$newsrel=$repository->getRepository('EMNewsBundle:NewsId')->findAll();
		$catn=$catnew_table->findAll();
		$cat=$cat_table->findAll();
		if($status=='All')
		{
			$news = $n_table->findAll();	
		}
		else
		{
			$news = $n_table->findBy(array('status'  => $status ));
		}
		return $this->render('EMNewsBundle:New:list.html.twig',
                        array('news' => $news,
                              'catn' => $catn,
                              'cat' => $cat,
                              'newsrel'=>$newsrel
                        ));
	
	}
        
        public function createUrlAction($slug){
            $url="";
            $url=$slug;
            return $url;
            
        }
        
        public function showNewAction($slug)
        {
            // use the $slug variable to query the database
            $repository=$this->getDoctrine();
	    $news_table=$repository->getRepository('EMNewsBundle:News');   
            $news = $news_table->findOneBySlug($slug);
            /*services.yml*/
         //   $utils = $this->get('em_service');
        //    $utils->findAuthorAction('1');
           // echo $news->getAuthor();
            return $this->render('EMNewsBundle:Blog:show.html.twig', array(
                'slug' => $slug,
                'news' => $news,
            ));
        }
        public function findAuthorAction($id){
          $repository = $this->getDoctrine()->getRepository('EMNewsBundle:Users');
	  $user=$repository->findOneById($id);  
          return $user;
        }
        
        public function showComboLanguagesAction($countryid){
          $utils = $this->get('em_service');
          $user = $this->container->get('security.context')->getToken()->getUser();
          $languages=$utils->findLanguagesByAuthorAndCountryAction($countryid,$user->getId());
         // print_r($languages);
         // exit();
          return $this->render('EMNewsBundle:New:_comboLanguages.html.twig', array(
                'languages' => $languages
            ));
        }
	
        public function editNewsAction(Request $request,$id){
            $em = $this->getDoctrine()->getManager();
            $categories=$em->getRepository('EMNewsBundle:Categories')->findAll();
            $languages=$em->getRepository('EMNewsBundle:Languages')->findAll();
            $countries=$em->getRepository('EMNewsBundle:Geography')->findBy(array('level'=>2));
            $new= $em->getRepository('EMNewsBundle:News')->find($id);
           
           
            if (!$new) {
                throw $this->createNotFoundException(
                    'No product found for id '.$id
                );
            }
            $form = $this->createForm(new NewType(), $new);
            if($request->getMethod() == 'POST'){
            $form->bind($request);
            $new->setDateUpdated( new \DateTime());
            $em->flush();
            return $this->redirect($this->generateUrl('em_news_list',array('status'=>'All')));
            }
            else
            {
             return $this->render('EMNewsBundle:New:new.html.twig', array(
			'form' => $form->createView(),
                        'step' =>4,
			'status_form'=>0,
			'categories'=>$categories,
                        'languages'=>$languages,
                        'countries'=>$countries
                     ));
            
            }
        }
        
       
}
